package com.wwwarehouse.resource_center.fragment.sales_Inventory_statistics;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.time_pick.DatePickerDialog;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.adapter.salesInventory_statistics.FilterMultipleDoubleAdapter;
import com.wwwarehouse.resource_center.bean.sales_inventory_statistics.CustomerSupplierResponseBean;
import com.wwwarehouse.resource_center.bean.sales_inventory_statistics.GetSignSupplierBuInfoBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.DDMDEvent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * 项目中的抽屉布局(多选)
 */

public class DeskDrawerMultipleDoubleFragment extends BaseFragment implements View.OnClickListener {
    private View mRootView;
    private TextView mTitleTxt;
    private GridView mGridView;
    private TextView mTitleTxt2;
    private GridView mGridView2;
    private TextView mSelectDateTv;
    private RelativeLayout mSelectDateRl;
    private Button mRestBtn;
    private Button mCompleteBtn;

    private String mTitle;
    private CustomerSupplierResponseBean mFilterList;
    private List<CustomerSupplierResponseBean.SupplierBusBean> supplierBusBeanList;
    private String mTitle2;
    private FilterMultipleDoubleAdapter mAdapter;
    private FilterMultipleDoubleAdapter mAdapter2;
    private int mColumns;

    private String date;
    private String toYear;
    private String toMonth;
    private String toDay;

    private static final String KEY_TITLE = "KEY_TITLE";
    private static final String KEY_LIST = "KEY_LIST_1";
    private static final String KEY_TITLE_2 = "KEY_TITLE_2";
    private static final String KEY_LIST_2 = "KEY_LIST_2";
    private static final String KEY_COLUMNS = "KEY_COLUMNS";

    public static final DeskDrawerMultipleDoubleFragment newInstance(String title, String title2, CustomerSupplierResponseBean filterList, List<CustomerSupplierResponseBean.SupplierBusBean> supplierBusBeanList, int columns) {
        DeskDrawerMultipleDoubleFragment deskDrawerMultipleFragment = new DeskDrawerMultipleDoubleFragment();

        Bundle bundle = new Bundle();
        bundle.putString(KEY_TITLE, title);
        bundle.putSerializable(KEY_LIST, filterList);
        bundle.putString(KEY_TITLE_2, title2);
        bundle.putSerializable(KEY_LIST_2, (Serializable) supplierBusBeanList);
        bundle.putInt(KEY_COLUMNS, columns);

        deskDrawerMultipleFragment.setArguments(bundle);

        return deskDrawerMultipleFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_desk_drawer_multiple_double_r, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
        initData();

    }

    private void initData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mTitle = bundle.getString(KEY_TITLE);
            mFilterList = (CustomerSupplierResponseBean) bundle.getSerializable(KEY_LIST);
            mTitle2 = bundle.getString(KEY_TITLE_2);
            supplierBusBeanList = (List<CustomerSupplierResponseBean.SupplierBusBean>) bundle.getSerializable(KEY_LIST_2);
            mColumns = bundle.getInt(KEY_COLUMNS);

            mTitleTxt.setText(mTitle);
            mGridView.setNumColumns(mColumns);
            mTitleTxt2.setText(mTitle2);
            mGridView2.setNumColumns(mColumns);
            mAdapter = new FilterMultipleDoubleAdapter(mActivity, mFilterList, mFilterList.getSupplierBus(), true, new FilterMultipleDoubleAdapter.OnClickListener() {

                @Override
                public void onSupplierClickListener() {
                    if (mAdapter.getmSelectedSupplier().size() == 0)
                        getAllCustomerSupplier();
                    else
                        getCustomerSupplier();
                }

                @Override
                public void onCustomerClickListener() {

                }
            });
            mGridView.setAdapter(mAdapter);

            mAdapter2 = new FilterMultipleDoubleAdapter(mActivity, mFilterList, mFilterList.getSupplierBus(), false, new FilterMultipleDoubleAdapter.OnClickListener() {

                @Override
                public void onSupplierClickListener() {

                }

                @Override
                public void onCustomerClickListener() {
                    getRelationBusinessUnitList();
                }
            });
            mGridView2.setAdapter(mAdapter2);
            java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = format.format(System.currentTimeMillis());
            String[] dateString = date.split(" ");
            String[] dates = dateString[0].split("-");
            toYear = dates[0];
            toMonth = dates[1];
            toDay = dates[2];
            mSelectDateTv.setText(dateString[0]);
        }
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    private void initView() {
        mTitleTxt = findView(mRootView, R.id.tv_title);
        mGridView = findView(mRootView, R.id.gv_content);
        mTitleTxt2 = findView(mRootView, R.id.tv_title2);
        mGridView2 = findView(mRootView, R.id.gv_content2);
        mSelectDateTv = findView(mRootView, R.id.select_date_tv);
        mSelectDateRl = findView(mRootView, R.id.select_date_rl);
        mRestBtn = findView(mRootView, R.id.btn_reset);
        mCompleteBtn = findView(mRootView, R.id.btn_complete);

    }

    /**
     * 获取客户列表
     */
    private void getCustomerSupplier() {
        Map map = new HashMap();

        map.put("relationType", "CUSTOMER");
        List<Long> supplierBuIds = new ArrayList<>();

        for (CustomerSupplierResponseBean.SupplierBusBean busBean : mAdapter.getmSelectedSupplier()) {
            supplierBuIds.add(Long.parseLong(busBean.getSupplierBuId()));
        }
        map.put("supplierBuIds", supplierBuIds);

        NoHttpUtils.httpPost(ResourceConstant.URL_GET_CUSTOMER_SUPPLIER, map, onResponseListener, 0);
    }

    /**
     * 获取总的客户列表
     */
    private void getAllCustomerSupplier() {
        Map map = new HashMap();

        map.put("relationType", "CUSTOMER");

        map.put("supplierBuIds", getmBusinessUnitIds());

        NoHttpUtils.httpPost(ResourceConstant.URL_GET_CUSTOMER_SUPPLIER, map, onResponseListener, 0);
    }

    /**
     * 获取客户对应供应商是否存在关系
     */
    private void getRelationBusinessUnitList() {
        Map<String, Object> map = new HashMap<>();
        List<String> customerBuIds = new ArrayList<>();
        for (CustomerSupplierResponseBean.CustomerBusBean busBean : mAdapter2.getmSelectedCustomer()) {
            customerBuIds.add(busBean.getCustomerBuId());
        }
        if (customerBuIds.size() == 0) {
            if (mAdapter.getmSelectedSupplier().size() == 0)
                getAllCustomerSupplier();
            else
                getCustomerSupplier();
            return;
        }
        map.put("customerBuIds", customerBuIds);
        map.put("relationType", "SUPPLIER");
        map.put("supplierBuInfo", supplierBusBeanList);
        NoHttpUtils.httpPost(ResourceConstant.GET_SIGN_SUPPLIER_BU_INFO, map, onResponseListener, 1);
    }

    private NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode()) && commonClass.getData() != null) {
                        mFilterList = JSON.parseObject(commonClass.getData().toString(), CustomerSupplierResponseBean.class);
                        List<CustomerSupplierResponseBean.CustomerBusBean> customerBusBeanList = new ArrayList<>();
                        for (CustomerSupplierResponseBean.CustomerBusBean customerBusBean : mAdapter2.getmSelectedCustomer()) {
                            boolean isContains = false;
                            for (CustomerSupplierResponseBean.CustomerBusBean customerBusBean1 : mFilterList.getCustomerBus()) {
                                if (customerBusBean.getCustomerBuId().equals(customerBusBean1.getCustomerBuId())) {
                                    isContains = true;
                                }
                            }
                            if (isContains)
                                customerBusBeanList.add(customerBusBean);
                        }
                        mAdapter2.setmSelectedCustomer(customerBusBeanList);
                        mAdapter.setmList(mFilterList);
                        mAdapter.notifyDataSetChanged();
                        mAdapter2.setmList(mFilterList);
                        mAdapter2.notifyDataSetChanged();
                    } else {
                    }
                    break;
                case 1:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        List<GetSignSupplierBuInfoBean> mList2 = JSON.parseArray(commonClass.getData().toString(), GetSignSupplierBuInfoBean.class);
                        List<CustomerSupplierResponseBean.SupplierBusBean> supplierBusBeanList = new ArrayList<>();
                        for (GetSignSupplierBuInfoBean buInfoBean : mList2) {
                            if (buInfoBean.getIsRelation().equals("1")) {
                                CustomerSupplierResponseBean.SupplierBusBean supplierBusBean = new CustomerSupplierResponseBean.SupplierBusBean();
                                supplierBusBean.setSupplierBuId(buInfoBean.getSupplierBuId());
                                supplierBusBean.setSupplierBuName(buInfoBean.getSupplierBuName());
                                supplierBusBeanList.add(supplierBusBean);
                            }
                        }
                        mFilterList.setSupplierBus(supplierBusBeanList);
                        mAdapter.setmList(mFilterList);
                        mAdapter.notifyDataSetChanged();
                        mAdapter2.setmList(mFilterList);
                        mAdapter2.notifyDataSetChanged();
                    } else {
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
        }
    };

    private void initEvent() {
        mRestBtn.setOnClickListener(this);
        mCompleteBtn.setOnClickListener(this);
        mSelectDateRl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_reset) {
            date = null;
            mSelectDateTv.setText(getString(R.string.resource_pls_select_date));
            mAdapter.setmSelectedSupplier(new ArrayList<CustomerSupplierResponseBean.SupplierBusBean>());
            mAdapter2.setmSelectedCustomer(new ArrayList<CustomerSupplierResponseBean.CustomerBusBean>());

            getAllCustomerSupplier();

//            EventBus.getDefault().post(new DDMDEvent("reset"));

        } else if (id == R.id.btn_complete) {
            CustomerSupplierResponseBean customerSupplierResponseBean = new CustomerSupplierResponseBean();

            customerSupplierResponseBean.setCustomerBus(mAdapter2.getmSelectedCustomer());
            customerSupplierResponseBean.setSupplierBus(mAdapter.getmSelectedSupplier());

            if (mAdapter2.getmSelectedCustomer().size() == 0 && mAdapter.getmSelectedSupplier().size() == 0)
                customerSupplierResponseBean = null;
            EventBus.getDefault().post(new DDMDEvent(date, customerSupplierResponseBean));

            ((BaseCardDeskActivity) mActivity).hideDrawerLayout();
        } else if (id == R.id.select_date_rl) {
            new DatePickerDialog.Builder(getActivity())
                    .setTitle(getString(R.string.resource_select_date_effective)).setMinYear(Integer.parseInt(toYear)).setMinMonth(Integer.parseInt(toMonth)).setMinDay(Integer.parseInt(toDay))
                    .setOnDateSelectedListener(new DatePickerDialog.OnDateSelectedListener() {

                        @Override
                        public void onDateSelected(String s) {
                            mSelectDateTv.setText(s);
                            java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("HH:mm:ss");
                            String time = format.format(System.currentTimeMillis());
                            date = s + " " + time;
                        }

                        @Override
                        public void onCancel() {

                        }
                    })
                    .create()
                    .show();

        }
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    private List<String> getmBusinessUnitIds() {
        List<String> list = new ArrayList<>();
        for (CustomerSupplierResponseBean.SupplierBusBean supplierBusBean : supplierBusBeanList) {
            list.add(supplierBusBean.getSupplierBuId());
        }
        return list;
    }
}
